package com.devunion.salon.server.rpc;

import org.gwtwidgets.server.spring.GWTSpringController;
import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.orm.jpa.JpaCallback;
import com.devunion.salon.client.rpc.VendorService;
import com.devunion.salon.client.app.bean.VendorModel;
import com.devunion.salon.core.model.Vendor;
import com.devunion.salon.server.jpa.utils.ModelQueryHelper;
import com.devunion.salon.server.jpa.utils.ObjectTransformer;
import com.extjs.gxt.ui.client.data.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import java.util.List;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: Andrei
 * Date: 08.03.2009
 * Time: 0:16:20
 * To change this template use File | Settings | File Templates.
 */
public class VendorServiceImpl  extends GWTSpringController implements VendorService {
     private JpaTemplate jpaTemplate;

  
    public PagingLoadResult<VendorModel> findVendors(BasePagingLoadConfig config) {
        List<Vendor> objects = ModelQueryHelper.executeFind(jpaTemplate, config, "select v from Vendor v ", "v", null);
        Long count = (Long) ModelQueryHelper.executeCount(jpaTemplate, config, "select count(v) from Vendor v ", "v", null);
        List<VendorModel> result = new ArrayList<VendorModel>(objects.size());
        for (Vendor vendor : objects) {
            result.add(ObjectTransformer.translate(vendor));
        }
        return new BasePagingLoadResult<VendorModel>(result, config.getOffset(), count.intValue());

    }

    public JpaTemplate getJpaTemplate() {
        return jpaTemplate;
    }

    public void setJpaTemplate(JpaTemplate jpaTemplate) {
        this.jpaTemplate = jpaTemplate;
    }

    public boolean updateVendor(final String origCode, final String code, final String address) {
        Integer success = (Integer)jpaTemplate.execute(new JpaCallback() {
            public Object doInJpa(EntityManager entityManager) throws PersistenceException {
                entityManager.getTransaction().begin();
                Query query = entityManager.createQuery("UPDATE Vendor v SET v.code=:newCode WHERE v.code=:code");
                query.setParameter("newCode", code);
                query.setParameter("code", origCode);
                Object result = query.executeUpdate();
                entityManager.getTransaction().commit();
                return result;
            }
              
        });
        return success != 0;
    }
}
